var express = require('express')
var bodyParser = require('body-parser')
var fs = require('fs')
var multer = require('multer')
var ejs = require('ejs')

var app = express()
app.set('view engine','ejs')

var createFolder = function (folder) {
    try {
        fs.accessSync(folder)
    } catch {
        fs.mkdirSync(folder)
    }
}
var uploadFolder = './upload/'
createFolder(uploadFolder)

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, uploadFolder)
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname)
    }
})
var upload = multer({
    storage: storage
})

var jsonParser = bodyParser.json()
var urlencodedParser = bodyParser.urlencoded({
    extended: false
})

app.get('/', function (req, res) {
    res.send("hello world")
})

app.get('/form/:name', function (req, res) {
    /* var form = fs.readFileSync('./form.html', {
        encoding: "utf-8"
    })
    res.send(form) */
    // Or
    /* res.sendFile(__dirname+'/form.html') */

    //使用模板引擎
    var person = req.params.name
    res.render('form',{person:person})
})

app.post('/upload', upload.single('logo'), function (req, res) {
    res.send({
        'ret_code': 0
    })
})

app.post('/', function (req, res) {
    console.dir(req.body)
    res.send(req.body)
})

app.listen(3000);